package com.wlstock.funi.runnable;

import com.wlstock.funi.R;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.app.FundAsyTask.TaskLitener;
import com.wlstock.funi.app.FundAsyTask.TaskResultListener;
import com.wlstock.funi.utils.HttpUtils;
import com.wlstock.funi.utils.IOUtils;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.NotiUtils;
import com.wlstock.funi.utils.StockUtils;
import com.wlstock.funi.utils.ToastUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;


public class ZXMaxCount {
	public static final int BSFLAG_BUY = 1;
	public static final int BSFLAG_SAILE = 2;
	private JSONObject stock;
	private int bsFlag;
	private String stkCode;
	private String fxj;
	public RefreshListener pListener;

	private ZXMaxCount(){};
	public ZXMaxCount(int bsFlag, String stkCode) {
		super();
		this.bsFlag = bsFlag;
		this.stkCode = stkCode;
	}

	public ZXMaxCount(int bsflagBuy, String subCode,String fxj, JSONObject stock) {
		this(bsflagBuy, subCode);
		this.stock = stock;
		this.fxj   = fxj;
	}

	public void request(){
		if (!FundApplication.isLogSuccess) {
			NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.ID_LOG_OUTDATE, "登陆失效，请重新登陆", "无法获取股票数量", R.drawable.ic_exception);
			ToastUtils.showMiddleMsg(FundApplication.getInstance(), "尚未登录，无法获取股票数量");
			return;
		}
		
		FundAsyTask<Void, Void, String> priceTask = new FundAsyTask<Void, Void, String>();
		priceTask.backListener = new TaskLitener<Void, String>() {
			@Override
			public String doInBackground(Void... param) {
				HttpClient client = new DefaultHttpClient();
				try {
					// Request
					// URL:https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=submitOrder
					HttpPost buyPost = new HttpPost("https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=getMaxQty");
					HashMap<String, String> parmHash = new HashMap<String, String>();
					// market:1 market:2
					// secuid:A303112208 secuid:0186265187
					// stkcode:600658 (601 603)开头 stkcode:002021(300,000)
					// price:11.16
					// qty:100
					// bsflag:1
					// bsprop:0
					// type:stock

					parmHash.put("market", StockUtils.parseStkCode2Market(stkCode));
					parmHash.put("secuid", StockUtils.parseStkCode2SecuId(stkCode));
					parmHash.put("stkcode", stkCode);
					parmHash.put("price", fxj);
					parmHash.put("qty", "");
					parmHash.put("bsflag", "1");
					parmHash.put("bsprop", "0");
					parmHash.put("type", "stock");


					List<? extends NameValuePair> params = HttpUtils.getParms(parmHash);
					// Accept:application/json, text/javascript, */*
					// Accept-Encoding:gzip, deflate
					// Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
					// Connection:keep-alive
					// Content-Length:90
					// Content-Type:application/x-www-form-urlencoded
					// Cookie:JSESSIONID=Qk0HWprRL3fNvzrBxrP2hFZD0MmbtwQg4S9Qf1Fncm02QNykd5Lh!-908755652!297676372;
					// ssl=etrade-ssl-1
					// Host:etrade.cs.ecitic.com
					// Origin:https://etrade.cs.ecitic.com
					// Referer:https://etrade.cs.ecitic.com/ymtrade/stock/buy.jsp
					// User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
					// X-Requested-With:XMLHttpRequest
					HttpEntity entity = new UrlEncodedFormEntity(params);
					buyPost.setEntity(entity);
					buyPost.addHeader("Accept", "application/json, text/javascript, */*");
					buyPost.addHeader("Accept-Encoding","gzip, deflate");
					buyPost.addHeader("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6");
					buyPost.addHeader("Connection","keep-alive");
					buyPost.addHeader("Content-Type","application/x-www-form-urlencoded");
					buyPost.addHeader("Cookie",FundApplication.cookie);
					buyPost.addHeader("Referer","https://etrade.cs.ecitic.com/ymtrade/stock/buy.jsp");
					buyPost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");
					buyPost.addHeader("X-Requested-With","XMLHttpRequest");

					HttpResponse buyPostResponse = client.execute(buyPost);

					if (buyPostResponse.getStatusLine().getStatusCode() == 200) {
						String result = IOUtils.is2Str(buyPostResponse.getEntity().getContent());
						JSONObject obj = new JSONObject(result);
						if (obj.getString("cssweb_type").equals("success")) {
							return obj.getString("cssweb_msg");
						}
						FundApplication.getInstance().playSoundPool(NotiIdGenerator.GenerFrom.REALTRADE);
					}
					//除了上面这种情况以外都是错误
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					client.getConnectionManager().shutdown();
				}
				return null;
			}
		}; 
		
		priceTask.resultListener = new TaskResultListener<String>() {

			@Override
			public void onPostResult(String result) {
				// TODO Auto-generated method stub
				if (pListener!=null) {
					if (result!=null ) {
						pListener.onUpdateResponse(stkCode,stock,bsFlag,result);
					}else {
						pListener.onUpdateResponse(stkCode,stock,bsFlag,null);
					}
				}
			}
		};
		priceTask.execute();
	}

	
	public interface RefreshListener{
		public void onUpdateResponse(String stkCode,JSONObject stock,int bsFlag,String response);
	}
	

}
